using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.API.APPLications.Commands.ImmunityInfo;
using Traceability.API.Dtos;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.ImmunityInfo
{
    /// <summary>
    /// 获取所有免疫信息查询处理器
    /// </summary>
    public class GetAllImmunityInfoQueryHandler : IRequestHandler<GetAllImmunityInfoQuery, APIResult<PagedResultDto<ImmunityInfoDto>>>
    {
        private readonly MyDbContext _context;

        public GetAllImmunityInfoQueryHandler(MyDbContext context)
        {
            _context = context;
        }

        public async Task<APIResult<PagedResultDto<ImmunityInfoDto>>> Handle(GetAllImmunityInfoQuery request, CancellationToken cancellationToken)
        {
            APIResult<PagedResultDto<ImmunityInfoDto>> result = new APIResult<PagedResultDto<ImmunityInfoDto>>();
            
            try
            {
                var query = _context.ImmunityInfos.AsQueryable();

                // 搜索过滤
                if (!string.IsNullOrEmpty(request.SearchKeyword))
                {
                    query = query.Where(x => 
                        x.Way.Contains(request.SearchKeyword) || 
                        x.Function.Contains(request.SearchKeyword) || 
                        x.ProductionBatch.Contains(request.SearchKeyword));
                }

                var totalCount = await query.CountAsync(cancellationToken);

                var items = await query
                    .OrderByDescending(x => x.ID)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(x => new ImmunityInfoDto
                    {
                        ID = x.ID,
                        RearingDays = x.RearingDays,
                        Way = x.Way,
                        Function = x.Function,
                        ProductionBatch = x.ProductionBatch
                    })
                    .ToListAsync(cancellationToken);

                result.Data = new PagedResultDto<ImmunityInfoDto>
                {
                    Items = items,
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };

                result.Code = APIEnum.查询成功;
                result.Message = "获取免疫信息列表成功";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.查询失败;
                result.Message = $"获取免疫信息列表失败: {ex.Message}";
            }
            
            return result;
        }
    }
} 